#include <iostream>
#include <pthread.h>
#include <queue>

template <class T>
class Blockqueue
{
public:
    Blockqueue(int maxcap = 10) : _maxcap(maxcap), _hight_water(maxcap / 3)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_c_cond, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
    }
    ~Blockqueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }
    bool IsFull()
    {
        return _block_queue.size() == _maxcap;
    }
    bool IsEmpty()
    {
        return _block_queue.empty();
    }
    void pop(T *out)
    {
        pthread_mutex_lock(&_mutex);
        while (IsEmpty())
        {
            pthread_cond_wait(&_c_cond, &_mutex);
        }
        *out = _block_queue.front();
        _block_queue.pop();
        if (_block_queue.size() < _hight_water)
            pthread_cond_signal(&_p_cond);
        pthread_mutex_unlock(&_mutex);
    }
    void Equeue(const T &in)
    {
        pthread_mutex_lock(&_mutex);
        while (IsFull())
        {
            pthread_cond_wait(&_p_cond, &_mutex);
        }
        _block_queue.push(in);
        if (_block_queue.size() > _hight_water)
            pthread_cond_signal(&_c_cond);
        pthread_mutex_unlock(&_mutex);
    }

private:
    std::queue<T> _block_queue;
    int _maxcap;
    int _hight_water;
    pthread_mutex_t _mutex;
    pthread_cond_t _c_cond; // 消费者信号
    pthread_cond_t _p_cond; // 生产者信号
};